import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-10-20
 * Time: 19:56
 */
class Message{
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/message")
public class MessageWallDemo1 extends HttpServlet {

    private ObjectMapper objectMapper = new ObjectMapper();
    private List<Message> messageList = new ArrayList<>();
    //前端那边提交了请求之后就构造好Post请求发送给后端服务器,
    //这边要接收并保存好,返回响应
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        Message message = objectMapper.readValue(req.getInputStream(),Message.class);
        messageList.add(message);
        System.out.println("message : " + message);
        resp.getWriter().write("{\"ok\" : 1}");
    }

    //前端那边需要从后端服务器获取数据从而显示到页面上
    //前端那边构造Get请求来获取后端的数据
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        //将之前保存的请求数据转化成Json字符串然后返回个客户端(前端那边)
        String JsonString = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(JsonString);
    }
}
